# -*- coding: utf-8 -*-
"""
@Author  : lon91ong (lon91ong@gmail.com)
@Version : 0.9.9
"""

from os import path
from flask import Flask, request, Response
from xml.etree.ElementTree import fromstring #, tostring
from pinyin import get_initial as pyfirst

app = Flask(__name__)
#flatpth = 'D:\\Program Files\\仿真实验'
flatpth = path.dirname(path.realpath(__file__))
labfile = open(flatpth+'/Download/Updata/Download/download.xml',mode='r',encoding='utf-8')
labroot = fromstring(labfile.read())
labfile.close()

@app.route('/BizService.svc', methods=['POST'], strict_slashes=False)
def bizSv():
    global labroot
    reqStr = '' # 请求信息
    #userid =''  # 用户id
    dataStr = '' # 响应数据
    # 响应文本预制
    respStr = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><DoServiceResponse xmlns="http://www.ustcori.com/2009/10"><DoServiceResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Data i:nil="true"/><Message/><RecordCount>0</RecordCount><Status>Success</Status></DoServiceResult></DoServiceResponse></s:Body></s:Envelope>'
    #print('URL:\n',request.url)
    xmls = fromstring(request.data.decode('utf-8'))
    method = xmls.findall(".//{http://www.ustcori.com/2009/10}MethodName")[0].text
    null = None; false = False
    reqStr = eval(xmls.findall(".//{http://schemas.microsoft.com/2003/10/Serialization/Arrays}Value")[0].text)
    if method == 'FindByLABID':
        labid = reqStr
        lab = labroot.findall(".//Experiment[@ID='"+labid+"']")[0].attrib
        print('实验:',lab['Name'],'分类:',lab['Sort'])
        dataStr = '<DataString>[{"LabID":'+labid+',"LABNAME":"'+lab['Name']+'","LABTYPEID":null,"LABTYPENAME":"'+lab['Sort']+'","INTRODUTION":"","CONTENT":null,"THEORY":null,"INSTRUMENT":null,"QualifiedTime":null,"LabFileUrl":"'+pyfirst(lab['Name'],'').upper()+'.lab","LabUpTime":null,"SourceFileUrl":null,"SourceUpTime":null,"UpTime":"'+lab['UpTime']+'","UPUSER":null,"LabWeight":null,"ReportWeight":null,"ReportFileUrl":null,"ReportUpTime":null}]</DataString>'
    elif method == 'ucControlMethod':
        labid = str(reqStr['LabID'])
        #userid = reqStr['UserID']
        dataStr = '<DataString>192</DataString>'
    elif method == 'SetLabTimeRecord':
        labid = str(reqStr['LABID'])
        #userid = reqStr['USERID']
        dataStr = '<DataString>192</DataString>'
    elif method == 'JFIsAccess':
        #userid = reqStr
        dataStr = '<DataString>""</DataString>'
    insp = respStr.index('<Message/>') # 定位插入点
    #xmls = fromstring(respStr[:insp] + dataStr + respStr[insp:])
    #xmls.findall(".//{http://www.ustcori.com/2009/10}Data")[0].append(fromstring(dataStr))
    #return Response(tostring(xmls,'utf-8').decode('utf-8'), mimetype='text/xml')
    return Response(respStr[:insp] + dataStr + respStr[insp:], mimetype='text/xml')

@app.route('/FileTransfer.svc', methods=['POST'], strict_slashes=False)
def fTranS():
    respStr = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><UploadFileResponse xmlns="http://tempuri.org/"/></s:Body></s:Envelope>'
    return Response(respStr, mimetype='text/xml')
    
if __name__ == '__main__':
    app.run('127.0.0.1','9542')